﻿using Neo4j.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;
using static System.Windows.Forms.AxHost;

namespace WinFormsApp1.Websocket
{
    /// <summary>
    /// 服务端
    /// </summary>
    public class WSocket
    {
        //WebSocket对象
        public WebSocketServer _socketServer = null;
        List<WebSocketServiceHost> webSocketServiceHosts;
        public delegate bool SendDatas(string sData);
        public static event SendDatas SendDataEvent;
        public static event EventHandler<WSEvent> OnGetMsg;
        public WSocket()
        {
            try
            {
                //实例化
                _socketServer = new WebSocketSharp.Server.WebSocketServer("ws://172.18.8.69:9875");
                //添加WebSocket的服务处理类
                _socketServer.AddWebSocketService<WSocketHandle>("/wsRobot");
                WebSocketServiceManager wSocketServiceManager = _socketServer.WebSocketServices;
                webSocketServiceHosts = wSocketServiceManager.Hosts.ToList();
            }
            catch (Exception err)
            {
            }
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="Data"></param>
        public void SendData(string Data)
        {
            //第一种触发方式发送
            // SendDataEvent?.Invoke(Data);
            //第二种获取到session会话对象发送
            var session = webSocketServiceHosts[0].Sessions;//获取到session会话对象
            var sessionIds = session.ActiveIDs;//获取会话的IDs
            foreach (var sessionId in sessionIds)
            {
                //发送
                session.SendToAsync(Data, sessionId, new Action<bool>(t =>
                {
                    if (!t)
                    {
                        Console.WriteLine("发送失败");
                    }
                }));
            }
        }
        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            _socketServer.Start();
        }
        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            _socketServer.Stop();
        }

        public static void InvokeMsg(string msg, WSEvent e)
        {
            if (OnGetMsg != null)
            {
                OnGetMsg(msg, e);
            }
        }
    }

    /// <summary>
    /// Websoket的信息处理类
    /// </summary>
    public class WSocketHandle : WebSocketBehavior
    {
        public WSocketHandle()
        {
        }
        /// <summary>
        /// 关闭触发
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClose(CloseEventArgs e)
        {

        }
        /// <summary>
        /// 连接触发
        /// </summary>
        protected override void OnOpen()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnError(WebSocketSharp.ErrorEventArgs e)
        {
        }

        /// <summary>
        /// 接收信息触发
        /// </summary>
        /// <param name="e"></param>
        protected override async void OnMessage(MessageEventArgs e)
        {
            try
            {
                string data = e.Data;
                var e2 = new WSEvent();
                e2.OnProcess = SendMes;
                WSocket.InvokeMsg(data,e2);
            }
            catch (Exception err)
            {
               
            }
        }

        #region 发生消息
        private void SendMes(object data,EventArgs e)
        {
            if (State == WebSocketSharp.WebSocketState.Open)
            {
                if (Sessions.Count > 0)
                {
                    Send(data.ToString());
                }
            }
        }
        #endregion

        #region 其他
        public static string GetContendDir(string appName)
        {
            return "D:\\Program Files\\SendMailServer\\content" + "_" + appName;
        }
        #endregion
    }

    public class WSEvent:EventArgs
    {
        public string OutputArgs;
        public EventHandler OnProcess;
    }
}
